﻿namespace Admin.Crypto
{
    /// <summary>
    /// 命令行辅助类
    /// </summary>
    public static class CommandUtils
    {
        private static EnvPortDto _portDto;

        /// <summary>
        /// 获取 Env Port
        /// </summary>
        public static EnvPortDto EnvPort
        {
            get
            {
                if (_portDto == null)
                    throw new ArgumentNullException("_portDto");

                return _portDto;
            }
        }

        /// <summary>
        /// 解析命令行参数并以字典返回
        /// </summary>
        /// <param name="args">命令行参数</param>
        /// <returns></returns>
        public static Dictionary<string, string> ParseArgs(string[] args)
        {
            var parsedArgs = new Dictionary<string, string>();

            foreach (var arg in args)
            {
                if (arg.StartsWith("--"))
                {
                    var parts = arg.Split(new[] { '=' }, 2);
                    var key = parts[0].Substring(2);
                    var value = parts.Length > 1 ? parts[1] : null;
                    parsedArgs[key] = value;
                }
            }

            return parsedArgs;
        }

        /// <summary>
        /// 获取环境和端口
        /// </summary>
        /// <param name="dic">来自命令行的初始化配置字典</param>
        /// <returns></returns>
        public static EnvPortDto GetEnvPort(Dictionary<string, string> dic)
        {
            if (_portDto != null)
                return _portDto;

            _portDto = new EnvPortDto();
            if (dic.ContainsKey("environment"))
                _portDto.Env = dic["environment"];
            else
                _portDto.Env = Environment.GetEnvironmentVariable("RUN_ENV") ?? "Development";

            if (dic.ContainsKey("port"))
                _portDto.Port = dic["port"];
            else
                _portDto.Port = Environment.GetEnvironmentVariable("RUN_PORT") ?? "5001";

            return _portDto;
        }
    }

    /// <summary>
    /// 环境和端口dto
    /// </summary>
    public class EnvPortDto
    {
        /// <summary>
        /// 环境
        /// </summary>
        public string Env { get; set; } = string.Empty;
        /// <summary>
        /// 端口号
        /// </summary>
        public string Port { get; set; } = string.Empty;
    }
}
